# -*- coding: UTF-8 -*-
import json
import time
from tools.ReadJson import replace_json_value
from tools.Request_General import BaseAPI
from pyLib.databaseManage import APP_DATABASE
from pyLib.LogManage import LOG
from application.space_server_api import SpaceServer


class AppServer(BaseAPI):
    """app服务相关接口"""

    def delete_app_info(self, appID, space_id, cookie):
        """删除应用信息接口"""
        header = {"app": str(appID), "space": space_id, "cookie": cookie}
        r = self.request_send(headers=header)
        return r

    def initialization(self, appID, space_id, cookie):
        """初始化应用接口"""
        header = {"app": str(appID), "space": space_id, "cookie": cookie}
        r = self.request_send(headers=header)
        return r

    def all_use_module_info(self, appID, space_id, cookie):
        """获取应用下所有可用和已用过的组件信息"""
        header = {"app": str(appID), "space": space_id, "cookie": cookie}
        r = self.request_send(headers=header)
        return r

    def copy_element(self, payload):
        """
        复制元素的接口
        """
        r = self.request_send(json=payload)
        return r

    def copy_folders_elements(self, payload):
        """
        批量复制文件夹和元素
        """
        r = self.request_send(json=payload)
        return r

    def list_element(self, payload):
        """
        查询指定目录下元素列表信息:
        """
        r = self.request_send(params=payload)
        return r

    def list_all_elements(self):
        """
        查询所有元素列表信息:
        """
        r = self.request_send()
        return r

    def get_server_names(self, payload):
        """
        批量获取组件服务名
        """
        r = self.request_send(json=payload)
        return r

    def get_usable_element_info(self, payload):
        """
        根据文件夹id，元素名称元素类型查询可用的元素信息
        """
        r = self.request_send(json=payload)
        return r

    def move_element(self, payload):
        """移动文件夹或元素"""
        r = self.request_send(json=payload)
        return r

    def move_folders_elements(self, payload):
        """批量移动文件夹和元素"""
        r = self.request_send(json=payload)
        return r

    def get_element_folder(self, payload):
        """查询某文件夹下所有文件夹及元素信息"""
        r = self.request_send(json=payload)
        return r

    def get_server_names_contain_error(self, payload):
        """批量获取组件服务名带错误信息"""
        r = self.request_send(json=payload)
        return r

    def query_page_element(self):
        """查询指定app下的page类型元素信息"""
        r = self.request_send()
        return r

    def modify_element_name(self, payload):
        """修改元素名称,存在关联元素时也需修改关联元素名称"""
        r = self.request_send(json=payload)
        return r

    def search_element(self, payload):
        """搜索元素"""
        r = self.request_send(params=payload)
        return r

    def get_all_element(self):
        """查询所有元素基础信息"""
        r = self.request_send()
        return r

    def update_open_extend(self, payload):
        """用于用户选择是否继承于父级文件夹的权限还是自定义配置权限"""
        r = self.request_send(json=payload)
        return r

    def get_space_group_page(self, payload):
        """条件查询元素对应当前空间用户组列表接口(分页)"""
        r = self.request_send(params=payload)
        return r

    def get_user_info_permission(self, payload):
        """查询空间用户对当前元素是否分配过权限接口"""
        r = self.request_send(params=payload)
        return r

    def create_folder(self, payload):
        """
        创建文件夹
        """
        r = self.request_send(json=payload)
        return r

    def del_folder(self, *folderID):
        """
        删除文件夹
        """
        payload = [*folderID]
        r = self.request_send(json=payload)
        return r

    def del_folder_element(self, payload):
        """批量删除文件夹和元素"""
        r = self.request_send(json=payload)
        return r

    def edit_folder(self, payload):
        """修改文件夹信息"""
        r = self.request_send(json=payload)
        return r

    def get_folder_full(self, folderId):
        """查询文件夹全路径"""
        payload = {"folderId": str(folderId)}
        r = self.request_send(params=payload)
        return r

    def get_folderID_by_fullPath(self, fullPath, get_folder_id=False):
        """根据全路径查询folderId接口"""
        payload = {"fullPath": fullPath}
        r = self.request_send(params=payload)
        if get_folder_id:
            return r.json().get("data")
        return r

    def get_folder_info(self, folderId):
        """查询文件夹明细"""
        payload = {"folderId": folderId}
        r = self.request_send(params=payload)
        return r

    def get_folders(self, folderId):
        """查询文件夹列表"""
        payload = {"folderId": folderId}
        r = self.request_send(params=payload)
        return r

    def folder_update_open_extend(self, payload):
        """用于用户选择是否继承于父级文件夹的权限还是自定义配置权限"""
        r = self.request_send(json=payload)
        return r

    def get_group_info_permission(self, payload):
        """查询所有用户组带对文件夹是否分配过权限标记接口"""
        r = self.request_send(params=payload)
        return r

    def get_group_info_permission_page(self, payload):
        """查询所有用户组对文件夹是否分配过权限接口"""
        r = self.request_send(params=payload)
        return r

    def folder_get_user_info_permission(self, payload):
        """查询空间用户对当前文件夹是否分配过权限接口"""
        r = self.request_send(params=payload)
        return r

    def folder_get_space_group_page(self, payload):
        """条件查询文件夹对应当前空间用户组列表接口(分页)"""
        r = self.request_send(params=payload)
        return r

    def delete_element(self, payload):
        """删除元素实列"""
        r = self.request_send(json=payload)
        return r

    def check_element_exist(self, payload):
        """根据元素名称/类型/路径校验该元素是否已经存在"""
        r = self.request_send(params=payload)
        return r

    def check_element_exist_by_list(self, payload):
        """根据元素名称/类型/路径（或文件夹id）批量校验该元素是否已经存在"""
        r = self.request_send(json=payload)
        return r

    def confirm_element(self, payload):
        """元素实例创建确认"""
        r = self.request_send(json=payload)
        return r

    def get_element_info_by_type(self, elementType):
        """根据元素类型查询元素信息"""
        payload = {"elementType": elementType}
        r = self.request_send(params=payload)
        return r

    def get_element_infos(self, payload):
        """元素信息查询"""
        r = self.request_send(json=payload)
        return r

    def get_elements_protocol(self, payload):
        """
        根据组件使用的协议查询支持的元素实例
        """
        r = self.request_send(json=payload)
        return r

    def get_elements_by_protocol_list(self, payload):
        """
        根据组件使用的协议查询支持的元素实例(批量)接口
        """
        r = self.request_send(json=payload)
        return r

    def get_menu_list(self):
        """获取菜单列表接口"""
        r = self.request_send()
        return r

    def create_element(self, payload):
        """元素实例创建"""
        r = self.request_send(json=payload)
        return r

    def save_element(self, payload):
        """元素实例保存"""
        r = self.request_send(json=payload)
        return r

    def update_element(self, payload):
        """元素实例更新"""
        r = self.request_send(json=payload)
        return r

    def element_relations(self, payload):
        """获取某元素关联引用的元素列表接口"""
        r = self.request_send(params=payload)
        return r

    def cited_element_relations(self, payload):
        """获取某元素关联被引用的元素列表接口"""
        r = self.request_send(params=payload)
        return r

    def get_element_info_by_name(self, payload):
        """根据元素名称查询元素信息"""
        r = self.request_send(params=payload)
        return r

    def upgrade_element(self, payload):
        """元素升级接口"""
        r = self.request_send(json=payload)
        return r

    def upgrade_info(self, payload):
        """元素升级信息查询接口"""
        r = self.request_send(params=payload)
        return r

    def upgrade_log(self, upgradeLog_id):
        """根据升级记录主表id查询元素升级记录接口"""
        payload = {"id": upgradeLog_id}
        r = self.request_send(params=payload)
        return r

    def element_import(self, payload, filepath):
        """元素导入接口"""
        file = {'file': open(filepath, 'rb')}
        r = self.request_send(data=payload, files=file)
        return r

    def file_resolve(self, folderId, filepath):
        """元素导入结构解析接口"""
        file = {'file': open(filepath, 'rb')}
        r = self.request_send(data={"folderId": folderId}, files=file)
        return r

    def coercion_lack(self):
        """查询个人可新建组件"""
        r = self.request_send()
        return r

    def permission_create_element_list(self):
        """元素新建权限配置列表查询"""
        r = self.request_send()
        return r

    def edit_permission(self, payload):
        """权限编辑"""
        r = self.request_send(json=payload)
        return r

    def add_group_permission(self, payload):
        """新增用户组关联的权限数据"""
        r = self.request_send(params=payload)
        return r

    def delete_group_permission(self, payload):
        """删除用户组关联的权限数据"""
        r = self.request_send(params=payload)
        return r

    def move_group_permission(self, payload):
        """移动用户组关联的权限数据"""
        r = self.request_send(params=payload)
        return r

    def get_permission_by_element(self, payload):
        """根据元素id查询已分配权限列表"""
        r = self.request_send(params=payload)
        return r

    def get_permission_by_folder(self, payload):
        """根据文件夾id查询已分配权限列表"""
        r = self.request_send(params=payload)
        return r

    def get_enterprise_group_permission(self):
        """查询元素或文件夹中有配置 所有用户/企业所有用户组权限对应的组id"""
        r = self.request_send()
        return r

    def get_element_permission(self, payload):
        """元素权限查询"""
        r = self.request_send(json=payload)
        return r

    def get_user_elementInfo_permission(self, payload):
        """单个获取用户对元素的权限"""
        r = self.request_send(params=payload)
        return r

    def get_no_permission_list(self, payload):
        """获取无权限的元素列表"""
        r = self.request_send(json=payload)
        return r

    def get_same_element_list_by_target(self, payload):
        """目标文件夹下同名元素查询接口"""
        r = self.request_send(json=payload)
        return r

    def remove_user_permission(self, payload):
        """删除用户对应元素权限"""
        r = self.request_send(params=payload)
        return r

    def create_element_update(self, payload):
        """
        元素新建权限配置编辑
        """
        r = self.request_send(json=payload)
        return r


class OperateApp:
    """app服务操作"""

    def __init__(self, headers):
        self.headers = headers
        self.app_server = AppServer(headers)

    def create_level_folder(self, full_path):
        """
        创建多层级文件夹，从根目录开始
        :param full_path: 多层级文件夹路径：/Heytea/Common/Dimension/
        :return 文件夹id
        """
        folder_names = full_path.strip('/').split('/')
        parentId = "0"
        app_id = self.headers['app']
        for name in folder_names:
            self.app_server.create_folder({"name": name, "parentId": parentId})
            parentId = APP_DATABASE.execute_sql(
                f"SELECT id FROM `app{app_id}_folder_info` WHERE `name`='{name}' AND parent_id='{parentId}'")[0][0]
        folder_id = APP_DATABASE.execute_sql(
            f"SELECT id FROM `app{app_id}_folder_info` WHERE full_path='{full_path}'")[0][0]
        return folder_id

    def import_elements(self, filepath, targetfolderId, permission=None, check_status=False):
        """
        元素导入
        :param filepath: 待导入文件
        :param targetfolderId: 目标文件夹id
        :param permission: 导入权限
        :param check_status: 是否需要等待查询导入结果
        """
        data = None
        for one in range(5):
            r = self.app_server.file_resolve(targetfolderId, filepath)
            LOG.info(f"导入元素数据解析：{r.text}")
            # 文件解析数据
            data = r.json().get('data')
            if data:
                break
        assert data is not None, f"元素导入结构解析接口失败"
        # 替换权限字段
        if permission:
            replace_json_value(data, "importPermissionWay", permission)
        # 文件解析数据
        resolveElementFileVo = json.dumps(data)
        # 导入
        payload = {"folderId": targetfolderId, "isNeedBusinessData": True, "resolveElementFileVo": resolveElementFileVo}
        import_r = self.app_server.element_import(payload, filepath).json()
        assert import_r.get('status'), f"导入元素失败:{import_r.get('message')}"
        log_id = import_r.get('data').get("id")
        if check_status:
            while True:
                # 导入状态
                import_status = SpaceServer(self.headers).element_import_log(log_id).json().get("data").get("status")
                LOG.info(f"查询导入状态:{import_status}")
                if "SUCCESS" in import_status:
                    break
                time.sleep(3)

    def delete_elements_by_type(self, folderId, elementType):
        """
        在指定文件夹内，根据元素类型删除元素
        :param folderId: 文件夹id
        :param elementType: 元素类型
        """
        element_list = self.app_server.list_element({"folderId": folderId}).json().get("data")
        if isinstance(elementType, str):
            elementType = [elementType]
        # 待删除元素请求
        del_pay = [
            {
                "id": "1",
                "name": element_info.get("name"),
                "type": element_info.get("elementType"),
                "parentId": folderId
            }
            for element_info in element_list if element_info.get("elementType") in elementType
        ]
        self.app_server.del_folder_element(del_pay)


if __name__ == '__main__':
    # pass
    from application.general_create import COOKIE, APP_ID, SPACE_ID

    h = {"cookie": COOKIE, "language": "zh-cn", "app": APP_ID, "space": SPACE_ID}
    res = AppServer(h).get_folderID_by_fullPath("/test_dimension1_2",get_folder_id=True)
    print(res)
